import React from 'react';
import {Form, Row, Col, Button, DatePicker, message ,Divider,Select,Input} from 'antd';
import StatisticsBox from '../../components/box/statistics';
import {sessionManager} from '../../utils/sessionStorage';
import AdjustHis from './AdjustHis';
import {injectIntl} from 'react-intl';
import Grid from '../../components/table/grid';
import axios from 'axios';
import moment from 'moment';
import { getYear } from '../../utils/Array';
import qs from 'qs';
const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const createForm = Form.create;
const Option = Select.Option;
class merchantStatistics extends React.Component {
  constructor(props) {
    super(props);
    this.common = this.props.intl.messages.common;
    this.columns = [
      {
        title: '用户账号',
        width: '150',
        dataIndex:'account',
        key: 'account'
      },
      {
        title: '名称',
        dataIndex: 'company_name',
        key: 'company_name',
        width: '150',
      },
      {
        title: '公司地址',
        dataIndex: 'company_address',
        key: 'company_address',
        width: '150',
      },
      {
        title: '公司电话',
        dataIndex: 'company_phone',
        key: 'company_phone',
        width: '150',
      },
      {
        title: '负责人姓名',
        dataIndex: 'chief_name',
        key: 'chief_name',
        width: '150',
      },
      {
        title: '状态',
        dataIndex: 'STATUS',
        key: 'STATUS',
        width: '150',
        render: (text) => (
          text.STATUS == 0 ? '未结算' : '已结算'
        )
      },
      {
        title: '账单金额（元）',
        dataIndex: 'fee_total',
        key: 'fee_total',
        width: '150',
      },
      {
        title: this.common.operation,
        key: 'action',
        fixed: 'right',
        width: 200,
        render: (text, record) => (
          <div>
						<span>
								<a onClick={() => this.goLink(text, record, 'ledgerMonthDetail')}>结算明细</a>
								<Divider type="vertical"/>
						</span>
            <span>
								<a onClick={() => this.goLink(text, record, 'childSettlelist')}>下级结算列表</a>
						</span>
          </div>
        )
      }
    ];
    this.state = {
      params:{
      },
      summary: [],
      visible: false,
      refresh:0
    }
  }

  componentWillMount() {
    this.getBillTotal()
  }

  getBillTotal(start, end){
    const NowDateStart= start || moment(new Date()).format('YYYY.MM.DD');
    const NowDateEnd= end || moment(new Date()).format('YYYY.MM.DD');
    if (this.props.location.state) {
      sessionManager.set('childSettleRecord', this.props.location.state.record);
    }
    if (this.props.location.state) {
      const childSettleParam = {
        userId: this.props.location.state.record ? this.props.location.state.record.userId: '',
        timeBegin: this.props.location.state.params.timeBegin,
        timeEnd: this.props.location.state.params.timeEnd
      };
      sessionManager.set('childSettleParam', JSON.stringify(childSettleParam));
      this.userId = childSettleParam.userId;
    } else {
      this.setState({
        params: JSON.parse(sessionManager.get('childSettleParam'))
      });
      console.log(this.state.params);
      this.userId = this.state.params.userId;
    }
    axios.get('/api/settlement/billSplit/splitRecord',{params:{
        timeBegin:NowDateStart,
        timeEnd:NowDateEnd
      }}).then(res=>{
      if(res&&res.code=='200'){
        const billData=res.data;
        this.setState({
          summary: [
            {
              num: billData.settlementPower||'',
              actions:() =>{
                return (
                  <div className="textLeft leftBill">
                    <div><span className="label">结算电费</span> <span>{billData.total_power_fee}</span> 元</div>
                    <div><span className="label">结算服务费</span> <span>{billData.total_service_fee}</span> 元</div>
                    <div><span className="label">结算电量</span> <span>{billData.total_power}</span> 元</div>
                  </div>
                )
              }
              // style:{width:400}
            },
            {
              num: billData.total_fee||'',
              unit:'元',
              desc: '结算总费用',
              btn:()=>{
                return(
                  <a onClick={this.loockDetail} className="a-leftBtn">查看明细</a>
                )
              }
            },
            {
              num: billData.settlementService||'',
              actions:() =>{
                return (
                  <div className="textLeft leftBill">
                    <div><span className="label">实际电量</span> <span>{billData.selfTotalPower}</span> 元</div>
                    <div><span className="label">实际电费</span> <span>{billData.selfTotalPowerFee}</span> 元</div>
                    <div><span className="label">实际服务费</span> <span>{billData.selftTotalServiceFee}</span> 元</div>
                  </div>
                )
              }
            },
            {
              num: billData.selfTotalFee||'',
              unit:'元',
              desc: '实际总费用'
            }
          ],
          NowDateStart:NowDateStart,
          NowDateEnd:NowDateEnd,
          params:{
            timeBegin:NowDateStart,
            timeEnd:NowDateEnd,
            code: sessionManager.get('childSettleRecord').CODE, //上级投资人code
            userId: sessionManager.get('childSettleParam').userId
          }
        },()=>{
          let GRIDHTML=<Grid url="api/settlement/billSplit/settlementChild" columns={this.columns} refresh={this.state.refresh}  params={this.state.params}/>
          this.setState({
            GRIDHTML:GRIDHTML
          })

        });
      }
    })
  }
  handleCancel = () => {
    this.setState({
      visible: false,
    })
  };

  formSubmit=(data)=>{
    this.setState({
      params: Object.assign(this.state.params, {...data}),
      refresh: this.state.refresh + 1
    }, () => {
      let GRIDHTML=<Grid url="api/settlement/billSplit/settlementChild" columns={this.columns} refresh={this.state.refresh}  params={this.state.params}/>
      this.setState({
        GRIDHTML:GRIDHTML
      });
    });
  }

  goLink = (text, record, link) => {
    sessionManager.set('merchantTimeBegin', this.state.NowDateStart);
    sessionManager.set('merchantTimeEnd', this.state.NowDateEnd);
    sessionManager.set('merchantUserId', text.userId);
    this.props.history.push({pathname: `/finance/${link}`, state: {record: text}});
  };

  // submitSettle = () => {
  //   axios.post('/api/settlement/unSettled/submitSettle', {...{splitTime: this.state.totalData.splitTime}}).then(res => {
  //     if (res && res.code == 200) {
  //       if (res.data > 0) {
  //         message.success('提交结算操作成功')
  //       } else {
  //         message.error('提交结算操作失败')
  //       }
  //     }
  //   })
  // };

  transFormNull=(data)=>{
    for(let i=0;i<data.length;i++){
      if(!data[i].id){
        data[i].id=i
      }
    }
    return data
  }

  transformData=(data)=>{
    return data;
  };

  endTimeLess = (rule, value, callback) => {

    if (value.isAfter(moment().format('YYYY.MM.DD'))) {
      callback(`请选择${moment().format('MM月DD日')}之前的时间`);
    } else {
      callback();
    }
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!!err) {
        return;
      }
      this.getBillTotal(values.rangeTime[0].format('YYYY-MM-DD'), values.rangeTime[1].format('YYYY-MM-DD'));
      // values.startEndTime[0]._i//开始时间
      // values.startEndTime[1]._i//结束时间
      // this.setState(Object.assign(this.state.params,values));
      // this.setState({
      // 	refresh:this.state.refresh+1
      // })
    });
  };

  handleSubmitList = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!!err) {
        return;
      }
      if (values.rangeTime && values.rangeTime.length) {
        values['timeBegin'] = values.rangeTime[0].format('YYYY-MM-DD');
        values['timeEnd'] = values.rangeTime[1].format('YYYY-MM-DD');
        delete values['rangeTime'];
      }
      this.formSubmit(values);
    });
  }

  render() {
    const token=(JSON.parse(sessionStorage.getItem("token"))||{}).token;
    let locale=sessionManager.get('locale');
    let exportQs=`${qs.stringify(this.state.params)}&token=${token}&locale=${locale}`;
    console.log('exportQs',exportQs);
    const {getFieldDecorator} = this.props.form;
    const dateFormat = 'YYYY-MM-DD';
    return (
      <div>
        <div className={"split-row"}>下级结算列表</div>
        <div>
          <Form className="SC-form">
            <Row gutter={14} type="flex">
              <Col xl={6} xxl={4}>
                <FormItem label={"所属组"}>
                  {getFieldDecorator('roleGroup',{
                    initialValue:''
                  })(
                    <Select placeholder={'处理方式'} allowClear={true}>
                      <Option value="">全部</Option>
                      <Option value="1">商户</Option>
                      <Option value="2">代理</Option>
                      <Option value="0">投资人</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col xl={6} xxl={4}>
                <FormItem label={"用户关键字"}>
                  {getFieldDecorator('userKeywords',)(
                    <Input placeholder={'账户，名称，公司地址'}/>
                  )}
                </FormItem>
              </Col>
              <Col xl={6} xxl={4}>
                <FormItem label={"负责人"}>
                  {getFieldDecorator('chiefName',)(
                    <Input placeholder={'负责人'} />
                  )}
                </FormItem>
              </Col>
              <Col xl={6} xxl={4}>
                <FormItem>
                  <Button type="primary" htmlType="submit"
                          onClick={this.handleSubmitList} className="ant-btn-84">{this.common.search}</Button>
                  <a href={`${axios.defaults.baseURL}/api/settlement/invoice/taxList/export?${exportQs}`}>
                    <Button type="primary">{this.common.exportStatement}</Button>
                  </a>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>
        {this.state.GRIDHTML}
        {/*<AdjustHis visible={this.state.visible} handleCancel={this.handleCancel}/>*/}
      </div>
    )
  }
}

merchantStatistics = createForm()(merchantStatistics);
export default injectIntl(merchantStatistics)
